package com.af.monitorModule.generator.service.impl;

import com.af.monitorModule.common.ResultEnum;
import com.af.monitorModule.common.util.TokenUtil;
import com.af.monitorModule.generator.entity.RoleUserVs;
import com.af.monitorModule.generator.entity.User;
import com.af.monitorModule.generator.entity.VO.MenuVo;
import com.af.monitorModule.generator.mapper.RoleUserVsMapper;
import com.af.monitorModule.generator.mapper.UserMapper;
import com.af.monitorModule.generator.service.UserService;
import com.af.monitorModule.response.exception.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyz_4dou
 * @since 2020-08-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleUserVsMapper userVsMapper;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private ValueOperations<String,Object> valueOperations;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public JSONObject Login(JSONObject data) {
        //创建查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("ename",data.get("login"));
        wrapper.eq("state",1);
        //查询
        User loginUser = userMapper.selectOne(wrapper);

        if(loginUser == null){
            throw new CustomerException(ResultEnum.USER_ISNOT_EXIST);
        }
        //获取加盐密码
        String password = DigestUtils.md5DigestAsHex((data.getString("pwd")+loginUser.getSalt()).getBytes());

        if ( ! password.equals(loginUser.getPassword())) {
            throw new CustomerException(ResultEnum.USER_PASSWORD_DECORRECT);
        }
        //生成token
        String token = tokenUtil.getToken(loginUser);
        valueOperations.set(loginUser.getUserId().toString(),token);

        JSONObject res= new JSONObject();
        res.put("token",token);
        res.put("code",200);
        res.put("userName",loginUser.getUserName());
        res.put("userId",loginUser.getUserId());
        return res;
    }

    @Override
    public JSONObject getTree(JSONObject data) {
        List<MenuVo> menu = userMapper.productList(Integer.valueOf(data.get("userId").toString()));
        JSONObject res= new JSONObject();
        res.put("treeMenu",menu);
        res.put("code",200);
        return res;
    }

    @Override
    public JSONObject checkOut(JSONObject data) {
        if (data == null){
            return ResultEnum.PARAM_INCORRECRT.getResult();
        }
        Integer id = data.getInteger("id");
        redisTemplate.delete(id.toString());
        return ResultEnum.OK.getResult();
    }

    @Override
    public JSONObject getAllAccount(String page, String limit, JSONObject search) {
        Page<User> p = new Page<User>(Integer.parseInt(page), Integer.parseInt(limit));
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("create_date");
        if (search != null)
            search.forEach((k,v)->{
                if (!"".equals(v.toString().trim())){
                    switchParam(k,v.toString(),wrapper);
                }
            });
        userMapper.selectPage(p,wrapper);
        JSONObject res = new JSONObject();
        res.put("data",p.getRecords());
        res.put("code",0);
        res.put("count",this.count(wrapper));
        res.put("msg","用户列表");
        return res;
    }

    @Override
    public JSONObject changeState(String user) {
        Integer id = Integer.valueOf(user);
        User change = userMapper.selectById(id);
        if (change == null){
            throw new CustomerException(ResultEnum.USER_ISNOT_EXIST);
        }
        change.setState(change.getState() == 1 ? 0:1);
        userMapper.updateById(change);
        return ResultEnum.OK.getResult();
    }

    @Override
    public void creatUser(String name,String bumen) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", name));
        if (user != null ){
            return;
        }
        String pinyin = name2pinyin(name);
        if ("".equals(pinyin)){
            return;
        }
        User userNew = new User().setUserName(name).setSex(1).setEname(pinyin).setSalt(pinyin)
                .setPassword(
                        DigestUtils.md5DigestAsHex(
                                (DigestUtils.md5DigestAsHex(
                                        ("Pass2"+pinyin.replace("af","")).getBytes()) + pinyin).getBytes()))
                .setCreateDate(LocalDateTime.now())
                .setUpdateDate(LocalDateTime.now()).setState(1).setVersion(0);
        int insert = userMapper.insert(userNew);
        User userTrue = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", name));
        userVsMapper.insert(new RoleUserVs().setUserId(userTrue.getUserId()).setRoleId(Integer.parseInt(bumen)));
    }


    /**
     * 用户管理页面查询参数添加
     * @param key
     * @param value
     * @param wrapper
     */
    public void switchParam(String key,String value ,QueryWrapper wrapper){
        switch (key){
            case "state":
            case "ename":
            case "user_name" :{
                wrapper.eq(key,value);
                break;
            }
            case "startTime":{
                wrapper.ge("create_date",value);
                break;
            }
            case "endTime":{
                wrapper.le("create_date",value);
                break;
            }
        }
    }

    public String name2pinyin(String name){
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        //拼音小写
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //不带声调
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //要转换的中文，格式，转换之后的拼音的分隔符，遇到不能转换的是否保留   wo,shi,zhong,guo,ren,，hello
        try {
            return "af_" + PinyinHelper.toHanYuPinyinString(name, format, "", true);
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return "";
    }


}
